package com.xiaochi.auth.domain.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.gson.Gson;
import com.xiaochi.auth.common.enums.AuthUserStatusEnum;
import com.xiaochi.auth.common.enums.IsDeletedEnum;
import com.xiaochi.auth.domain.constants.AuthConstants;
import com.xiaochi.auth.domain.convert.AuthUserBOConverter;
import com.xiaochi.auth.domain.entity.AuthUserBO;
import com.xiaochi.auth.domain.redis.RedisUtil;
import com.xiaochi.auth.domain.service.AuthUserDomainService;
import com.xiaochi.auth.infra.basic.entity.*;
import com.xiaochi.auth.infra.basic.service.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zqx
 * @since 2024/8/28
 */
@Service
@Slf4j
public class AuthUserDomainServiceImpl implements AuthUserDomainService {

    @Resource
    private AuthUserService authUserService;

    @Resource
    private AuthRoleService authRoleService;

    @Resource
    private AuthPermissionService authPermissionService;

    @Resource
    private AuthRolePermissionService authRolePermissionService;

    @Resource
    private AuthUserRoleService authUserRoleService;

    private final String salt = "chicken";

    @Resource
    private RedisUtil redisUtil;

    private String authPermissionPrefix = "auth.permission";

    private String authRolePrefix = "auth.role";

    private static final String LOGIN_PREFIX = "loginCode";


    @Override
    @SneakyThrows
    @Transactional //这个事务有手动的，在有需要的地方
    public Boolean register(AuthUserBO authUserBO) {
        //验证用户是否存在
        AuthUser exitAuthUser = new AuthUser();
        exitAuthUser.setUserName(authUserBO.getUserName());
        List<AuthUser> authUserList = authUserService.queryByCondition(exitAuthUser);
        if (authUserList.size() > 0){
            return true;
        }
        AuthUser authUser = AuthUserBOConverter.INSTANCE.authBOToEntity(authUserBO);
        if (StringUtils.isNotBlank(authUserBO.getPassword())){
            authUser.setPassword(SaSecureUtil.md5BySalt(authUser.getPassword(),salt));
        }
        if (StringUtils.isBlank(authUser.getAvatar())){
            authUser.setAvatar("http://116.196.87.225:9090/browser/xiaochi/70cd7a30ac1d470ebc5f965ec9656005~tplv-p14lwwcsbr-7.jpg");
        }
        if (StringUtils.isBlank(authUser.getNickName())){
            authUser.setNickName("xiaochi粉丝");
        }
        authUser.setIsDeleted(IsDeletedEnum.UN_DELETED_ENUM.getCode());
        authUser.setStatus(AuthUserStatusEnum.OPEN.getCode());
        Integer insert = authUserService.insert(authUser);
        //建立一个 初步的角色的关联
        AuthRole authRole = new AuthRole();
        authRole.setRoleKey(AuthConstants.NORMAL_USER);
        AuthRole roleResult = authRoleService.queryByCondition(authRole);
        Long roleId = roleResult.getId();
        Long userId = authUser.getId();
        AuthUserRole authUserRole = new AuthUserRole();
        authUserRole.setRoleId(roleId);
        authUserRole.setUserId(userId);
        authUserRole.setIsDeleted(IsDeletedEnum.UN_DELETED_ENUM.getCode());
        authUserRoleService.insert(authUserRole);
        // 要把当前用户的角色和权限都刷到我们的redis里

        //角色key
        String roleKey = redisUtil.buildKey(authRolePrefix, authUser.getUserName());
        List<AuthRole> roleList = new LinkedList<>();
        roleList.add(authRole);
        redisUtil.set(roleKey,new Gson().toJson(roleList));
        //根据roleid查询权限id
        AuthRolePermission authRolePermission = new AuthRolePermission();
        authRolePermission.setRoleId(roleId);
        List<AuthRolePermission> authRolePermissionList = authRolePermissionService.queryByCondition(authRolePermission);
        List<Long> permissionIdList = authRolePermissionList.stream().map(AuthRolePermission::getPermissionId).collect(Collectors.toList());
        //把权限id构建key 存到redis中
        List<AuthPermission> authPermissionList = authPermissionService.queryByPermissionList(permissionIdList);
        String permissionKey = redisUtil.buildKey(authPermissionPrefix, authUser.getUserName());
        redisUtil.set(permissionKey,new Gson().toJson(authPermissionList));

        return insert > 0;
    }

    @Override
    public Boolean update(AuthUserBO authUserBO) {
        AuthUser authUser = AuthUserBOConverter.INSTANCE.authBOToEntity(authUserBO);
        Integer count = authUserService.update(authUser);
        //有任何的更新，都要与缓存进行同步的修改
        return count > 0;
    }

    @Override
    public Boolean delete(AuthUserBO authUserBO) {
        AuthUser authUser = new AuthUser();
        authUser.setId(authUserBO.getId());
        authUser.setIsDeleted(IsDeletedEnum.DELETED_ENUM.getCode());
        Integer count = authUserService.update(authUser);
        return count > 0;
    }

    @Override
    public SaTokenInfo doLogin(String validCode) {
        String loginKey = redisUtil.buildKey(LOGIN_PREFIX, validCode);
        String openId = redisUtil.get(loginKey);
        if (StringUtils.isBlank(openId)){
            return null;
        }
        AuthUserBO authUserBO = new AuthUserBO();
        authUserBO.setUserName(openId);
        this.register(authUserBO);
        StpUtil.login(openId);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return tokenInfo;
    }

    @Override
    public AuthUserBO getUserInfo(AuthUserBO authUserBO) {
        AuthUser authUser = new AuthUser();
        authUser.setUserName(authUserBO.getUserName());
        List<AuthUser> authUserList = authUserService.queryByCondition(authUser);
        if (CollectionUtils.isEmpty(authUserList)){
            return new AuthUserBO();
        }
        AuthUser user = authUserList.get(0);
        return AuthUserBOConverter.INSTANCE.authEntityToBo(user);
    }
}
